package org.water.sys.web;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.water.common.jcaptcha.CaptchaUtil;
import org.water.common.param.ConstParams;


/**
 * 验证码
 * @author qzy
 *
 */
@Controller()
@RequestMapping("/jcaptcha")
public class JcaptchaController {

    private static Logger log=LogManager.getLogger(JcaptchaController.class);
	
	public JcaptchaController() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 生成验证码
	 * @param request
	 * @param response
	 */
	@RequestMapping("/img")
	public void generateImg(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		// 设置相应类型,告诉浏览器输出的内容为图片
		response.setContentType("image/jpeg");
		// 不缓存此内容
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		try {
			StringBuffer code = new StringBuffer();
			BufferedImage image = CaptchaUtil.getInstance().genRandomCodeImage(code);
			request.getSession().removeAttribute(ConstParams.KEY_CAPTCHA);
			request.getSession().setAttribute(ConstParams.KEY_CAPTCHA, code.toString().toLowerCase());
			// 将内存中的图片通过流动形式输出到客户端
			ImageIO.write(image, "JPEG", response.getOutputStream());
			log.info("生成验证码:"+code.toString()+" session:"+request.getSession().getId());
		} catch (Exception e) {
			log.info("生成验证码失败");
		}
	}
}
